package com.global.college.api;


import com.google.gson.Gson;
import com.global.college.UserData;
import com.global.college.ui.bean.requestBean.AlipayParams;
import com.global.college.ui.bean.requestBean.WxParams;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.android.BuildConfig;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by fu on 2020/2/16.
 * Describe: 客户端请求
 */
@SuppressWarnings("unchecked")
public class AlipayRequestClient {

    private final static String TAG = "RequestClient";

    /**
     * 超时时间(秒)
     */
    public static final int DEFAULT_TIMEOUT = 1800;

    public static Observable.Transformer IO_UI = new ClassicIOTransformer();
    /**
     * 单例
     */
    private static AlipayRequestClient authRequestClient;

    private static HttpLoggingInterceptor BODY_LOGGER = new HttpLoggingInterceptor();
    private static HttpLoggingInterceptor BASIC_LOGGER = new HttpLoggingInterceptor();

    private Retrofit mRetrofit;

    private AliPayServerAPI serverApi;
    private String app = "app";


    public void setDebug() {
        if (BuildConfig.DEBUG) {
            BODY_LOGGER.setLevel(HttpLoggingInterceptor.Level.BODY);
            BASIC_LOGGER.setLevel(HttpLoggingInterceptor.Level.BASIC);
        } else {
            BODY_LOGGER.setLevel(HttpLoggingInterceptor.Level.NONE);
            BASIC_LOGGER.setLevel(HttpLoggingInterceptor.Level.NONE);
        }
    }

    private AlipayRequestClient() {
        //系统平台版本号
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);//超时时间
        builder.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);//上传超时时间
        builder.retryOnConnectionFailure(true);//启用自动重连
        //拦截器－添加公共字段
        //builder.addInterceptor(commonInterceptor);
        //builder.addNetworkInterceptor(new LoggingInterceptor());
        builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));//这是打印所有日志
        builder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request newRequest = chain.request().newBuilder().header("client-type", "app").build();
                return chain.proceed(newRequest);
            }
        });

        setDebug();
        OkHttpClient okHttpClient = builder.build();
        mRetrofit = new Retrofit.Builder()
                .baseUrl(AliPayURLs.BASE_URL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        serverApi = mRetrofit.create(AliPayServerAPI.class);
    }

    //外部调用
    @SuppressWarnings("unchecked")
    public static AlipayRequestClient getInstance() {
        if (null == authRequestClient) {
            authRequestClient = new AlipayRequestClient();
        }
        return authRequestClient;
    }

    /**
     * 19.微信支付v2版本 发起微信支付请求
     * body	商品描述
     * outTradeNo	 商户订单号
     * totalFee	订单总金额（元）
     * tradeType	交易类型,JSAPI支付,Native支付APP支付，MWEB H5支付
     * productId	产品id  当tradeType=Native 的时候必须带上productId
     * timeExpire	交易结束时间/订单失效时间 默认2小时,格式为yyyyMMddHHmmss，如2009年12月25日9点10分10秒表示为20091225091010
     * appId	默认uton在线 appid可不传，nft和其他调用必传appid
     */
    public Observable<String> wxPay(WxParams params) {
        String body = new Gson().toJson(params);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), body);
        return serverApi.wxPay(UserData.getInstance().getToken(), requestBody)
                .map(new HttpResultFunc<>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }
    /**
     * 20.发起支付宝支付
     * orderNo	订单号
     * totalAmount	订单支付金额
     * subject	商品标题
     * paySkillName	支付能力名称,取值： APP,或者 PC
     * returnUrl	回调地址
     */

    public Observable<String> aliPay(AlipayParams params) {
        String body = new Gson().toJson(params);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), body);
        return serverApi.aliPay(UserData.getInstance().getToken(), requestBody)
                .map(new HttpResultFunc<>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }
}